package com.cqc.vibratedemo;

import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.widget.CompoundButton;
import android.widget.Switch;
import android.widget.ToggleButton;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.switch1)
    Switch switch1;
    private Context context;
    @BindView(R.id.toggleButton)
    ToggleButton toggleButton;
    private Vibrator vibrator;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        context = this;
//        AudioAttributes audioAttributes = new AudioAttributes.Builder()
//                .setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
//                .setUsage(AudioAttributes.USAGE_GAME).build();

        vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ToastUtil.showShortToast(context, String.valueOf(isChecked));
                if (isChecked) {
                    vibrator.vibrate(2000);
//                    vibrator.vibrate(2000, audioAttributes);
                } else {
                    vibrator.cancel();
                }
            }
        });

        switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                ToastUtil.showShortToast(context, String.valueOf(isChecked));
                if (isChecked) {
                    long[] pattern = {1000, 2000};
                    int repeat = 0;
                    vibrator.vibrate(pattern, repeat);//repeat:-1时只震动一次；>=0时：index,就是数组pattern中的索引;其中数组的长度必须>1时，repeat才有效。当数组长度为1时，设置0是无效的。
                } else {
                    vibrator.cancel();
                }
            }
        });


    }
}
